package com.renyr.service;

import com.renyr.model.FilePathProperties;
import com.renyr.utils.Common;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@Service
public class ImgService {

	@Autowired
	private FilePathProperties properties;

	static String sep = System.getProperty("file.separator");
	
	public String saveImg(MultipartFile file) {
		String saveFileName = saveFile(file);
		return saveFileName;
	}

	public String saveImgs(MultipartFile[] files) {
		String saveFileNames = "";
		for (int i = 0; i <files.length; i++) {
			String saveFileName = saveFile(files[i]);
			
			if (i == files.length - 1) {
				saveFileNames += saveFileName;
			}else {
				saveFileNames += saveFileName+",";
			}
		}
		return saveFileNames;
	}
	
	public boolean deleteImg(String filename) {
		try {
			File file = new File(properties.getFilePath() + sep + filename);
	        if(file.exists() && file.isFile()) {
	        	file.delete();
	        }
			return true;
		} catch (Exception e) {
			return false;
		}
	}
	
	public boolean deleteImgs(String[] filenames) {
		try {
			for (int i = 0; i < filenames.length; i++) {
				File file = new File(properties.getFilePath() + sep + filenames[i]);
		        if(file.exists() && file.isFile()) {
		        	new Thread(()-> file.delete()).start();
		        }
			}
			return true;
		} catch (Exception e) {
			return false;
		}
	}
	
	private String saveFile(MultipartFile file) {
		String saveFileName = null;
		try {
			byte[] bytes = file.getBytes();
			String allfileName = file.getOriginalFilename();
			int index = allfileName.lastIndexOf(".");
			String suffix = allfileName.substring(index, allfileName.length());
			File dirPath = new File(properties.getFilePath());
			if (!dirPath.exists()){
				dirPath.mkdirs();
			}
			saveFileName = new Common().createImgName() + suffix;
			
			File uploadedFile = new File(properties.getFilePath() + sep + saveFileName);
			new Thread(() -> {
				try {
					FileCopyUtils.copy(bytes, uploadedFile);
				} catch (IOException e) {
					e.printStackTrace();
				}
			}).start();
			
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		return saveFileName;
	}
}
